<?php
namespace common\services;
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-15
 * Time: 11:11
 */

use common\models\LoginForm;
use common\models\User;
use frontend\models\SignupForm;
use frontend\modules\Api\services\CommonService;
use Yii;
use yii\base\DynamicModel;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class UserService
 * @package common\services
 * 用户相关服务
 */
class UserService
{
    /**
     * 登录token存储bucket
     */
    const TOKEN_BUCKET = 'Login:';

    /**
     * @var string
     * 错误信息
     */
    private static $errMsg ;


    /**
     * @param array $formData
     * @return mixed 注册成功返回新增用户uid
     * 用户注册 必须参数 mobile 手机号 password 密码
     */
    public static function register(array $formData)
    {
        $model = new SignupForm();
        $model->load($formData,'');
        if ($model->validate() && $model->signup()) {
            return $model->insertUid;
        }else{
            self::$errMsg = current($model->getFirstErrors());
            return false;
        }
    }

    /**
     * @param array $formData
     * @return boolean
     * 用户登录 必须参数 mobile 手机号 password 密码
     */
    public static function loginByMobile(array $formData)
    {
        $model = new LoginForm();
        $model->load($formData,'');
        if ($model->validate() && $model->login()) {
            return true ;
        }else{
            self::$errMsg = current($model->getFirstErrors());
            return false;
        }
    }

    /**
     * @param array $formData
     * @throws
     * @return boolean
     * 用户登录 必须参数 mobile 手机号 sms_code 短信验证码
     */
    public static function loginByCode(array $formData)
    {
        $form = DynamicModel::validateData([
            'username' => ArrayHelper::getValue($formData,'username'),
            'sms_code' => ArrayHelper::getValue($formData,'sms_code'),
        ],[
            [['username','sms_code'], 'required'],
        ]);
        if ($form->hasErrors()) {
            self::$errMsg = current($form->getFirstErrors());
            return false;
        }
        // 校验验证码是否正确 放在控制器校验吧
//        if(!CommonService::checkSmsCode($form->username,$form->sms_code)) {
//            self::$errMsg = '验证码校验失败';
//            return false;
//        }
        // 进行用户登录
        return Yii::$app->user->login(User::findByUsername($form->username));
    }

    /**
     * @param $token
     * @throws
     * @return mixed 成功返回uid 失败返回null
     * 根据token进行 登录
     */
    public static function loginByToken($token)
    {
        $redis  = Yii::$app->get('redis');
        $uid    = $redis->get(self::TOKEN_BUCKET.$token);
        return $uid ?: null;
    }

    /**
     * @throws
     * @param $uid
     * @param $password
     * @return boolean
     * 给用户设置新密码
     */
    public static function setNewPassword($uid,$password)
    {
        $user = Yii::$app->user->identity->findIdentity($uid);
        if(!$user){
            throw new Exception('用户获取失败,uid:'.$uid);
        }
        /** @var $user \common\models|User*/
        $user->setPassword($password);//重新生成密码
        $user->save();
        if($user->hasErrors()){
            throw new Exception('设置失败,errMsg:'.current($user->getFirstErrors()));
        }else{
            return true ;
        }
    }

    /**
     * @param $token
     * @param $uid
     * @throws \yii\base\InvalidConfigException
     * @return boolean
     * 存储登录后的token标识与uid对应关系 有效期7天
     */
    public static function storeLoginToken($token,$uid)
    {
        $redis = Yii::$app->get('redis');
        $redis->setex(self::TOKEN_BUCKET.$token,3600*24*7,$uid);
        return true;
    }

    /**
     * @param $token
     * @throws
     * @return boolean
     * 接口方式登录状态退出
     */
    public static function logoutByToken($token)
    {
        $redis = Yii::$app->get('redis');
        $redis->del(self::TOKEN_BUCKET.$token);
        // 清除session相关
        Yii::$app->user->logout();
        return true;
    }

    /**
     * @param $phone
     *
     * @return array|\yii\db\ActiveRecord|null
     * @desc 根据手机号获取用户信息
     */
    public static function getUserByPhone($phone)
    {
        return User::find()->where([
            'mobile' => $phone
        ])->asArray()->one();
    }


    /**
     * @param $uid
     *
     * @return array|\yii\db\ActiveRecord|null
     * @desc 根获UID取用户信息
     */
    public static function getUserByUid($uid)
    {
        return User::find()->where([
            'id' => $uid
        ])->asArray()->one();
    }
    /**
     * @param $uid
     *
     * @return array|\yii\db\ActiveRecord|null
     * @desc 根获UID取用户信息
     */
    public static function getUsernameByUid($uid)
    {
        $user = User::find()->where([
            'id' => $uid
        ])->asArray()->one();
        return $user['username'];
    }
    /**
     * @return string
     * 返回错误信息
     */
    public static function getError()
    {
        return self::$errMsg;
    }
}
